import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Vector;


public class HTMLThread extends Thread {

/*~~~~ ATTRIBUTES ~~~~*/

	public static final String nl = "\r\n";
	public static final String nlbr = "<br />\r\n";
	protected InputNavigator objInputNavigator;
	protected Vector<Event> objEvents;
	protected String outputFileHTML;
	protected String inputFileHTML;


/*~~~~ CONSTRUCTORS ~~~~*/

	public HTMLThread(Vector<Event> objEvents, String inputFileHTML, String outputFileHTML) {
		this.objEvents = objEvents;
		this.inputFileHTML = inputFileHTML;
		this.outputFileHTML =  outputFileHTML;
	}


/*~~~~ RUN ~~~~*/

	public void run() {
		try {
			InputNavigator objInputNavigator = new InputNavigator(inputFileHTML);
			BufferedWriter objBufferWrite = new BufferedWriter(new FileWriter(outputFileHTML));
			String[] strInfos = new String[7]; 
			String strLine, strDate = "";

			/**/System.out.println("Now writing data on \"" + outputFileHTML + "\"...");/**/
			while ((strLine = objInputNavigator.readLine()) != null) {
				/* Only when encounter key words, we add informations */
				if(strLine.equals("EVENTS_HERE")) {
					strLine = "        <h1>EVENTS LIST</h1>" + nl +
							  "            <div id=\"eventi\">" + nl;
					if (objEvents.isEmpty()) {
						strLine += "                Vuoto" + nl;
					} else {

						for (int i = 0; i < objEvents.size(); i++){
							/* 22/04/2009 22:00 */
							strInfos[0] = objEvents.get(i).getStrWhen().substring(0, 10);
							strInfos[1] = objEvents.get(i).getStrWhen().substring(10, 16);
							strInfos[2] = objEvents.get(i).getStrWho();
							strInfos[3] = objEvents.get(i).getUrlWho();
							strInfos[4] = objEvents.get(i).getStrWhat();
							strInfos[5] = objEvents.get(i).getUrlWhat();
							strInfos[6] = objEvents.get(i).getStrWhere();

							/* New date = new listing */
							if (!strDate.equals(strInfos[0])) {
								if(!strDate.equals(""))
									strLine += "                </ul>" + nl;
								strLine += "                <b>" + strInfos[0] + "</b>" + nl
										+ "                <ul>" + nl;
								strDate = strInfos[0];
							}
								strLine += "                    <li>" + " " + strInfos[1] + ": <a href=\"" + strInfos[3] + "\"><b>" + strInfos[2] + "</b></a> =&gt; <a href=\"" + strInfos[5] + " \">" + strInfos[4] + "</a>, " + strInfos[6] + "</li>" + nl;
						}
						strLine += "                </ul>" + nl
								 + "            </div>" + nl;

					}
				}

				objBufferWrite.write(strLine + nl);
				objBufferWrite.flush();
			}

			objInputNavigator.close();
			objBufferWrite.close();
			/**/System.out.println("Data wrote on \"" + outputFileHTML + "\"...");/**/

		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
